<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

App::uses('CakeEmail', 'Network/Email');

class UsersController extends AppController{
    
    public $uses = array('User','Organization','Project','ProjectMember','ProjectTeam','Request','Member','OrgMember','Team');
    public $components=array('Search');
    var $helpers = array('Ajax'); //, 'Chat.AjaxChat'
    
     public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('add','forgotPw'); // Letting users register themselves
    }
    
    //AUTORIZACION
    public function isAuthorized($user) {
        // All registered users can add posts
        if (in_array($this->action, array('add','forgotPw', 'requests','requestResponse','login','logout','home','view','index','antes'))){
            return true;
        }

        // The owner of a post can edit and delete it
        if (in_array($this->action, array('edit', 'delete'))) {
           if (isset($user['role']) && $user['role'] === 'admin') {
                return true;
           }
        }

        return parent::isAuthorized($user);
    }
    

    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->Session->setFlash('Bienvenido: '.$this->Auth->user('username'));
                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('Invalid username or password, try again'));
            }
        }
    }
    
     public function forgotPw() {
        if ($this->request->is('post')) {
            if ($this->User->findByEmail($this->request->data['User']['email'])) {
                $email = new CakeEmail('fast');
                $mySend   = $email//->template('welcome')
                            ->emailFormat('text')
                            ->to($this->request->data['User']['email'])
                            ->from('admin@example.com')
                            ->send();
//                $email->to($this->request->data['User']['email'])
//                    ->subject('My subject')
//                    ->message('My message')    ;
//                $mySend = $email->send();;
                if ($mySend) {
                    $this->Session->setFlash('The e-mail was sent!', 'default', array('class' => 'alert alert-success'));
                }
                else {
                    $this->Session->setFlash('An unexpected error occurred while sending the e-mail.', 'default', array('class' => 'alert alert-error'));
                }
                    
                
                //$this->Session->setFlash('Se enviara email a: '.$this->request->data['User']['email']);
            } else {
                $this->Session->setFlash(__('Invalid username or password, try again'));
            }
        }
    }
    

    public function logout() {
        $this->Session->delete('Organization');
        $this->redirect($this->Auth->logout());
    }

    public function antes() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    public function index() {
        $this->User->recursive = 0;
        $conditions=$this->Search->getConditions();
        $this->set('pages', $this->paginate(null,$conditions));
    }
    
    public function view($id = null) {
         if ($id==null){
             $id=$this->Auth->user('id');
         }
         $id2=$this->Auth->user('id');
         if ($id2==$id){
            
            $pro=$this->ProjectMember->find('all', array('conditions' => array('ProjectMember.user_id =' => $id)));
            $this->set('projects',$pro);
         }
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }
     public function requests() {
         
         $id=$this->Auth->user('id');
         
        $requests=$this->Request->find('all', array('conditions' => array('Request.user_to =' => $id)));
        $this->set('requests',$requests);
        
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }
    public function requestResponse($id,$response){
        
        $responseRQ= array('id'=> $id,'accepted'=>$response);
        
        if ($this->Request->save($responseRQ)) {
            $rq=$this->Request->findById($id);
            
            //ACTUALIZAR MEMBER
            
            $this->Member->updateAll(
                    array('Member.state'=>($response+1)),
                    array('Member.user_id ='=>$this->Auth->user('id'),'Member.team_id ='=>$rq['Request']['team_id'])
                    );
            //ACTUALIZAR ORG_MEMBER
            $team=$this->Team->findById($rq['Request']['team_id']);
            
            $org=$this->Organization->findById($team['Team']['organization_id']);
            if ($org['Organization']['creator_id']!=$this->Auth->user('id')){
            $this->OrgMember->updateAll(
                    array('OrgMember.state'=>($response+1)),
                    array('OrgMember.user_id ='=>$this->Auth->user('id'),
                        'OrgMember.organization_id ='=>$team['Team']['organization_id'],
                        'OrgMember.state ='=> 0)
                    );
             }
              
             
             //AGREGAR A LOS PROYECTOS
             $project_teams=$this->ProjectTeam->findAllByTeamId($team['Team']['id']);
             if(count($project_teams)>=0){
                 foreach($project_teams as $p_t){
                     $project_member=$this->ProjectMember->findAllByProjectIdAndUserId($p_t['ProjectTeam']['project_id'],$this->Auth->user('id'));
                     //$this->Session->setFlash(__('ANTES'.count($project_member)));
                     if(count($project_member)==0){
                         //   $this->Session->setFlash(__('DENTRO'));
                         $p_member=array('project_id'=>$p_t['ProjectTeam']['project_id'],
                             'user_id'=>$this->Auth->user('id'),
                             'team_id'=>$team['Team']['id']);
                         $this->ProjectMember->save($p_member);
                         
                     }
                 }
             }
             
            $this->redirect(array('action' => 'requests'));
        }
    }
    
    public function home() {
        if ($this->Auth->user()!=NULL){
            $id=$this->Auth->user('id');

            $this->User->id = $id;
            if (!$this->User->exists()) {
                throw new NotFoundException(__('Invalid user'));
            }
            $this->set('user', $this->User->read(null, $id));

            $org=$this->Organization->find('all', array('conditions' => array('Organization.creator_id =' => $id)));
            $this->set('orgs',$org);
            
            $pro=$this->Project->find('all', array('conditions' => array('Project.creator_id =' => $id)));
            $this->set('projects',$pro);

        }
    }

    public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
            
            $someone = $this->User->findByUsername($this->data['User']['username']);
            if ($someone!= NULL) $this->set('exist',$this->data['User']['username']);  //ZP: es necesario que el username no se repita
            
            else {
                if ($this->User->save($this->request->data)) {
                    if ($this->Auth->login()) {//ZP:Hago logIn
                        $this->Session->setFlash(__('The user has been saved'));
                        $this->redirect(array('action' => 'view',));
                    }
                    else{
                        $this->Session->setFlash(__('Error en logear al usuario'));
                        $this->redirect(array('action' => 'login'));
                    }
//                    $id = $this->User->id;
//                    $this->request->data['User'] = array_merge($this->request->data['User'], array('id' => $id));
//                    $this->Auth->login($this->request->data['User']);
//                    $this->Session->setFlash(__('The user has been saved'));
//                    $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                }
            }
        }
    }

    public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
            unset($this->request->data['User']['password']);
        }
    }

    public function delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->User->delete()) {
            $this->Session->setFlash(__('User deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        $this->redirect(array('action' => 'index'));
    }
    
    
    
}
?>
